# -*- coding: utf-8 -*-
import xdrlib, sys
import xlrd
import os
from moduleMap import *
def open_excel(file='file.xls'):
    try:
        data = xlrd.open_workbook(file)
        return data
    except Exception, e:
        print str(e)


# 根据索引获取Excel表格中的数据   参数:file：Excel文件路径     colnameindex：表头列名所在行的所以  ，by_index：表的索引

def excel_table_byindex(file='file.xls', colnameindex=0, by_index=0):
    data = open_excel(file)
    # print data.sheets()
    table = data.sheets()[0]
    nrows = table.nrows  # 行数
    ncols = table.ncols  # 列数
    colnames = table.row_values(colnameindex)  # 某一行数据
    # print colnames
    list = []
    moduleCol=unicode('模块','utf-8')
    for rownum in range(1, nrows):

        row = table.row_values(rownum)
        if row:
            app = {}
            for i in range(len(colnames)):

                if colnames[i] == moduleCol:
                    print colnames[i] + ": " +row[i]
                app[colnames[i]] = row[i]
            list.append(app)
    return list

def getModuleBugDic(path):
    listArr = excel_table_byindex(path)
    moduleCol=unicode('模块','utf-8')
    bugDic = {}
    for dicRow in listArr:
        module = dicRow[moduleCol]
        if module == "" or module == None:
            continue

        if module in bugDic:
            value = bugDic[module]
            value = value + 1
            bugDic[module] = value
        else:
            bugDic[module] = 1
    print bugDic
    return bugDic
def getBugNumByModule(module,path):
    bugDic = getModuleBugDic(path)
    if module in mapModule:
        realModule = mapModule[module]
        bugNum = 0
        if "," in realModule:
            moduleArr = realModule.split(",")
            for m in moduleArr:
                mUtf = unicode(m,'utf-8')
                if mUtf in bugDic:
                    bugNum = bugNum +bugDic[mUtf]
        else:
            bugNum = bugDic[realModule]
        return bugNum
    else:
        return 0

def main():
    currentPath=os.path.abspath(sys.argv[0])
    path=os.path.dirname(currentPath)+"/../bugFile/"+"bug_201607.xls"
    # path = os.path.dirname(currentPath)+"/bug_201607.xls"
    bugnum = getBugNumByModule("campaign",path)
    print bugnum
    # print path
    # tables = excel_table_byindex(path)
    # for row in tables:
    #     print row


if __name__ == "__main__":
    main()
